<?php
declare(strict_types=1);

namespace App\Admin\Middleware;

use App\Admin\Service\System\SystemUserService;
use DI\DependencyException;
use DI\NotFoundException;
use Newbie\Exception\NoPermissionException;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class PermissionMiddleware implements MiddlewareInterface {
    /**
     */
    public function process (Request $request, callable $handler): Response {
        if ($request->route) {
            $permission = $request->route->param('permission', '');
            // 注解权限为空，则放行
            if (empty($permission->code)) {
                return $handler($request);
            }
            $loginUser = user();
            if ($loginUser->isSuperAdmin()) {
                return $handler($request);
            }
            $this->checkPermission($permission->code);
        }
        return $handler($request);
    }

    /**
     * 检查权限
     * @param string $codeString
     * @return bool
     * @throws DependencyException
     * @throws NotFoundException
     */
    protected function checkPermission (string $codeString): bool {
        $codes = container()->get(SystemUserService::class)->getInfo()['codes'];
        foreach (explode(',', $codeString) as $code) {
            if (in_array(trim($code), $codes)) {
                return true;
            }
        }
        throw new NoPermissionException(
            t('system.no_permission') . ' -> [ ' . request()->path() . ' ]'
        );
    }
}